﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Resources;
using InterOp;
using Security;
using System.Linq;
using Storage;
using Storage.EntityModels;
using Groupware;
using Stats;

namespace GUI
{
    internal class SocialNetworkUserInfo
    {
        public string SocialNetworkName { get; set; }
        public string SocialNetworkToken { get; set; }
    }

    public partial class EditProfile : TripLOA.GUI.internationalization.LOABasePage
    {
        private List<string> snBuddyList = new List<string>();
        //private MembershipUser userSecurity;
        private TripLoaUser us;
        private Profile userProfile;

        protected void Page_Load(object sender, EventArgs e)
        {
            //userSecurity = Membership.GetUser();
            us = TripLoaUserManager.Instance.getUser(User.Identity.Name);
            MaskedEditValidator1.MaximumValue = DateTime.Now.ToShortDateString();

           
            if ((Request.QueryString["auth_token"] != null) && !IsPostBack)
            {
                //Here we handle data loaded from the SN
                handleSnData();
            }
            else
            {
                if (!IsPostBack)
                {
                   
                    userProfile = us.GetProfile();

                    //Label_UserNick.Text = this.userProfile.Nickname;
                    Label_UserNick.Text = userProfile.Username;
                    RadioButton_Smoker_Yes.Checked = userProfile.Smoker == Storage.EntityModels.Smoker.Smoker;
                    RadioButton_Smoker_No.Checked = userProfile.Smoker == Storage.EntityModels.Smoker.NotSmoker;

                    RadioButton_Female.Checked = (userProfile.Gender == Storage.EntityModels.Gender.Female);
                    RadioButton_Male.Checked = (userProfile.Gender == Storage.EntityModels.Gender.Male);
                    Txt_Birthday.Text = (
                                            userProfile.Birthday != null
                                                ? userProfile.Birthday.Value.ToString(
                                                      CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern,
                                                      CultureInfo.CurrentCulture)
                                                : ""
                                        );
                    Txt_City.Text = userProfile.City;
                    Txt_Address.Text = userProfile.Address;
                    Txt_Name.Text = userProfile.Name;
                    Txt_Surname.Text = userProfile.Surname;
                    Txt_Email.Text = userProfile.Email;
                    Txt_PhoneNumber.Text = userProfile.PhoneNumber;
                    
                    DropDownListBirthDay.SelectedValue= convertFromPrivacyLevel(userProfile["Birthday"]);
                    DropDownListPrivacyCity.SelectedValue = convertFromPrivacyLevel(userProfile["City"]);
                    DropDownListPrivacyAddress.SelectedValue = convertFromPrivacyLevel(userProfile["Address"]);
                    DropDownListPrivacyName.SelectedValue = convertFromPrivacyLevel(userProfile["Name"]);
                    DropDownListPrivacySurname.SelectedValue = convertFromPrivacyLevel(userProfile["Surname"]);
                    DropDownListPrivacyPhoneNumber.SelectedValue = convertFromPrivacyLevel(userProfile["PhoneNumber"]);


                    


                    //Loads the veichles

                    if (UserManager.getUserVehicleType(us.UserID)==0)
                        CheckBoxVehicles.Items[0].Selected=true;

                    if (UserManager.getUserVehicleType(us.UserID) == 1)
                        CheckBoxVehicles.Items[1].Selected = true;

                    if (UserManager.getUserVehicleType(us.UserID) == 2)
                        CheckBoxVehicles.Items[2].Selected = true;

                    if (UserManager.getUserVehicleType(us.UserID) == 3)
                        CheckBoxVehicles.Items[3].Selected = true;

                    if (UserManager.getUserVehicleType(us.UserID) == 4)
                        CheckBoxVehicles.Items[4].Selected = true;

                    if (UserManager.getUserVehicleType(us.UserID) == 5)
                        CheckBoxVehicles.Items[5].Selected = true;
                    if (UserManager.getUserVehicleType(us.UserID) == 6)
                        CheckBoxVehicles.Items[6].Selected = true;

                }
            }
        }


        private Storage.PrivacyLevel convertToPrivacyLevel(string val)
        {
            switch (val)
            {
                case "0":
                    return Storage.PrivacyLevel.NotVisible;
                   

                case "1":
                    return Storage.PrivacyLevel.Low;
                   

                case "2":
                    return Storage.PrivacyLevel.Medium;
                   

                case "3":
                    return Storage.PrivacyLevel.High;
                    

                default:
                    return Storage.PrivacyLevel.High;
                   
            }
        }

        private string convertFromPrivacyLevel(PrivacyLevel val)
        {
            switch (val)
            {
                case Storage.PrivacyLevel.NotVisible:
                    return "0";


                case Storage.PrivacyLevel.Low:
                    return "1";


                case Storage.PrivacyLevel.Medium:
                    return "2";


                case Storage.PrivacyLevel.High:
                    return "3";


                default:
                    return "3";

            }
        }

        private void handleSnData()
        {
            //Ge are getting back data from Facebook
            InterOpService intSrv = new InterOpService(InterOpService.ServiceType.Facebook, this);


            if ((bool) Session["importFriends"] == false)
            {
                //We import just the data of the profile
                UserData uDa = intSrv.importProfile(null);

                Txt_Name.Text = uDa.Name;
                Txt_Surname.Text = uDa.Surname;
                Txt_Birthday.Text =
                    uDa.Birthday.Value.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern,
                                                CultureInfo.CurrentCulture);

                Txt_City.Text = uDa.City;

                Txt_Address.Text = uDa.Address;

                RadioButton_Female.Checked = uDa.Gender == "Male" ? false : true;
                RadioButton_Male.Checked = uDa.Gender == "Male" ? true : true;

                Txt_Email.Text = uDa.Email;

                SocialNetworkUserInfo snUserData = new SocialNetworkUserInfo();
                snUserData.SocialNetworkName = "facebook";
                snUserData.SocialNetworkToken = uDa.UserID;
                Session["snUserData"] = snUserData;
            }
            else
            {
                //We import only the friends
                snBuddyList = intSrv.importFriends(null);

                GridView1.Visible = true;

                GridView1.DataBind();
            }
        }


        protected void Btn_ImportDataFromSN_Click(object sender, EventArgs e)
        {
            Session["importFriends"] = false;
            InterOpService intSrv = new InterOpService(InterOpService.ServiceType.Facebook, this);
            handleSnData();
            intSrv.Dispose();
        }

        protected void Btn_Confirm_Click(object sender, EventArgs e)
        {


            us = TripLoaUserManager.Instance.getUser(User.Identity.Name);
            userProfile = us.GetProfile();

            if (RadioButton_Female.Checked)
                userProfile.Gender = Storage.EntityModels.Gender.Female;
            if (RadioButton_Male.Checked)
                userProfile.Gender = Storage.EntityModels.Gender.Male;

            if (RadioButton_Smoker_No.Checked)
                userProfile.Smoker = Storage.EntityModels.Smoker.NotSmoker;
            if (RadioButton_Smoker_Yes.Checked)
                userProfile.Smoker = Storage.EntityModels.Smoker.Smoker;
            //FIX: todo validation
            if (Txt_Birthday.Text != "")
                userProfile.Birthday = DateTime.Parse(Txt_Birthday.Text, CultureInfo.CurrentCulture);
            userProfile.City = Txt_City.Text;
            userProfile.Address = Txt_Address.Text;
            userProfile.Name = Txt_Name.Text;
            userProfile.Surname = Txt_Surname.Text;
            userProfile.Email = Txt_Email.Text;
            userProfile.PhoneNumber = Txt_PhoneNumber.Text;
            //Here we have to save information about the social network

            // Qui ho aggiunto il controllo !(bool)Session["importFriends"] perchè:
            // Carico i solo i dati e li salvo => va tutto bene 
            // Quando vado ad aggiungere gli amici => trovo di nuovo Session["snUserData"] != null
            // e se non aggiungo il controllo !(bool)Session["importFriends"] tenta di inserire di
            // nuovo una entry in quella famosa tabella di cui non ricordo il nome
            // by Romina
            if (Session["snUserData"] != null && !(bool)Session["importFriends"])
            {
                SocialNetworkUserInfo snUserData = (SocialNetworkUserInfo) Session["snUserData"];
                saveSocialNetworkSubscription(snUserData, userProfile.Username);
                
            }


            //Checks if no vehicle is selected
            bool noChecked = true;
            foreach (ListItem v in CheckBoxVehicles.Items)
            {
                if (v.Selected)
                    noChecked=false;
            }

            //If there is no vehicle selected
            if (noChecked)
            {
                UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.NoOwnVehicle);
            }
            else
            {

                if (CheckBoxVehicles.Items[0].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.UtilitaryCarVehicleType);

                if (CheckBoxVehicles.Items[1].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.SedanCarVehicleType);

                if (CheckBoxVehicles.Items[2].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.SportCarVehicleType);

                if (CheckBoxVehicles.Items[3].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.SUVCarVehicleType);


                if (CheckBoxVehicles.Items[4].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.MPVCarVehicleType);


                if (CheckBoxVehicles.Items[5].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.MotorbikeVehicleType);

                if (CheckBoxVehicles.Items[6].Selected)
                    UserManager.setUserVehicleType(us.UserID, (int)StatsModule.vehicleTypes.NoOwnVehicle);

            }
 

              
            if (GridView1.Visible)
            {
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    GridViewRow row = GridView1.Rows[i];
                    bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

                    if (isChecked)
                    {
                        var test = GridView1.SelectedDataKey;

                        int u = 2;
                        u++;
                    }
                }
            }


            //Salvataggio livelli di privacy

            us.SetFieldPrivacyLevel("Name", convertToPrivacyLevel(DropDownListPrivacyName.SelectedValue));
            us.SetFieldPrivacyLevel("Surname", convertToPrivacyLevel(DropDownListPrivacySurname.SelectedValue));
            us.SetFieldPrivacyLevel("PhoneNumber", convertToPrivacyLevel(DropDownListPrivacyPhoneNumber.SelectedValue));
            us.SetFieldPrivacyLevel("Address", convertToPrivacyLevel(DropDownListPrivacyAddress.SelectedValue));
            us.SetFieldPrivacyLevel("Birthday", convertToPrivacyLevel(DropDownListBirthDay.SelectedValue));
            us.SetFieldPrivacyLevel("City", convertToPrivacyLevel(DropDownListPrivacyCity.SelectedValue));

            
            us.SaveProfile();


            Response.Redirect("~/secure/userProfile.aspx");
        }

        //Temporary implemented
        private void saveSocialNetworkSubscription(SocialNetworkUserInfo snUserData, string userName){
            //snUserData = new SocialNetworkUserInfo() {
            //    SocialNetworkName="facebook", 
            //    SocialNetworkToken="dsafsg"};
            

            TripLoaDataContext db = StorageManager.Instance.Entities;

            //Gets the social network
            var socialNetwork = (from socNet in db.SocialNetworks
                                 where socNet.Name == snUserData.SocialNetworkName
                                 select socNet).First();


            if (socialNetwork!=null)
            {
                //Gets the user
                var userNetwork = (from u in db.Users
                                   where u.Username == userName
                                  select u).First();

                var subscription = new SocialNetworkSubscribeDetails()
                {
                    User = userNetwork,
                    SocialNetwork = socialNetwork,
                    SocialNetworkUsername="",
                    SocialNetworkUserPassword="",
                    IsMaster=true,
                    UserToken = snUserData.SocialNetworkToken
                };
                db.SocialNetworkSubscribeDetails.InsertOnSubmit(subscription);

            }

            


                db.SubmitChanges();




            
            

        //    //We get a reference to the Social Network
        //    //Checks if this social network exists, otherwise it is created           
        //    if (!(userProfile.SocialNetworks.Exists(s => s.Name == snUserData.SocialNetworkName)))
        //    {
        //        userProfile.SocialNetworks.Add(new Storage.EntityModels.SocialNetwork() { Name = snUserData.SocialNetworkName });

        //    }
        //    //Get a reference to the social network, then through Subscribers it adds a new subscription
        //    userProfile.SocialNetworks.Find(s => s.Name == snUserData.SocialNetworkName).Subscribers.Add
        //        (new Storage.EntityModels.SocialNetworkSubscribeDetails() { UserToken = snUserData.SocialNetworkToken });

        //}

            }

        protected void l_btn_ImportAmici_facebook_Click(object sender, EventArgs e)
        {
            Session["importFriends"] = true;
            InterOpService intSrv = new InterOpService(InterOpService.ServiceType.Facebook, this);
            handleSnData();
            intSrv.Dispose();
        }

        protected void LinqDataSourceFriendsFromSN_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            //FacebookConnection fb = new FacebookConnection(this);
            //UserData me = fb.importProfile(null);
            //List<string> buddyList = fb.importFriends(null);

            //Controllo inutile, viene fatto sopra su Btn_Confirm_Click
            //if (GridView1.Visible == true)
            //{

            FriendsFromSNDataSource fs = new FriendsFromSNDataSource("facebook", snBuddyList, us);
            if (fs.Friends.Count != 0)
            {
                ButtonAddFriends.Visible = true;
            }
            e.Result = fs.Friends;
            //}
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            // Select the checkboxes from the GridView control

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;


                //TripLoaUser meUser = Security.TripLoaUserManager._instance.getUser(User.Identity.Name);


                if (isChecked)
                {
                    string u = GridView1.Rows[i].Cells[1].Text;
                    //Profile friendProfile = meUser.GetProfile(u);
                    Profile friendProfile = us.GetProfile(u);
                    //meUser.AddFriend(friendProfile.Id);
                    us.AddFriend(friendProfile.Id);
                }
            }
            ResourceManager rm = new ResourceManager(this.GetType());


             ButtonAddFriends.Enabled = false;

        }
    }
}